import React from 'react';
import { Message, Button } from '@teamix/ui';
import exceed from 'utils/apimap';
import CONSTANTS from 'utils/constants.js';
import BalloonConfirm from 'components/ballonConfirm';
import { YunxiaoIcon } from '@alife/devops-ui';
import './index.scss';
import intl from '../../../locale';

const prefix = 'account-message-content';
const { PLATFORM_TYPES } = CONSTANTS;
export default class Account extends React.PureComponent {
  state = {
    isUnbinding: false,
  };

  handleUnbind = (cb) => {
    // 在列表使用需要为list
    const { origin, accountInfo } = this.props;
    if (this.state.isUnbinding) {
      return;
    }
    this.setState({
      isUnbinding: true,
    });

    const { platform_type } = this.props.accountInfo;
    if (origin === 'list') {
      cb &&
        cb({
          submitting: true,
        });
    }

    exceed
      .fetch({
        api: 'projects.import.account.delete',
        params: { platform_type },
      })
      .then((result) => {
        this.setState({
          isUnbinding: false,
        });

        if (origin === 'list') {
          cb &&
            cb({
              submitting: false,
              visible: false,
            });
        }
        if (result.result) {
          Message.success({
            title: intl.get({
              id: 'code-assets.importProjectModal.accountMessage.UnbindSuccessfully',
              defaultMessage: '解除绑定成功',
            }),
          });

          if (accountInfo.bind_type === 'TOKEN') {
            this.props.unbindCallback();
          } else if (accountInfo.bind_type === 'GITEE_OAUTH') {
            // 因为tb不能上，这边手动调那边接口
            this.getAliens();
          } else {
            window.location.href = 'https://account.teambition.com/my/third';
          }
        } else {
          Message.error({
            title: intl.get({
              id: 'code-assets.importProjectModal.accountMessage.FailedToUnbind',
              defaultMessage: '解除绑定失败',
            }),
          });
        }
      })
      .fail((err) => {
        this.setState({
          isUnbinding: false,
        });

        Message.error({
          title: intl.get({
            id: 'code-assets.importProjectModal.accountMessage.FailedToUnbind',
            defaultMessage: '解除绑定失败',
          }),
        });

        if (origin === 'list') {
          cb &&
            cb({
              submitting: false,
            });
        }
        console.error(err);
      });
  };

  getAliens = () => {
    exceed
      .fetch({
        api: 'user.tb.aliens',
      })
      .then((result) => {
        const data = result.slice(1).find((item) => {
          return item.refer === 'gitee';
        });
        this.unbindTb(data.alienId);
      })
      .fail((err) => {
        console.error(err);
      });
  };

  unbindTb = (alienId) => {
    exceed
      .fetch({
        api: 'user.tb.aliens.delete',
        params: { alienId },
      })
      .then(() => {})
      .fail((err) => {
        console.error(err);
      });
  };

  render() {
    const { accountInfo, origin } = this.props;
    const platformName =
      (accountInfo.platform_type &&
        PLATFORM_TYPES[accountInfo.platform_type] &&
        PLATFORM_TYPES[accountInfo.platform_type].name) ||
      '';
    let platformHost;
    if (accountInfo.platform_type === 'PRIVATE_GITLAB') {
      platformHost = accountInfo.platform_host;
    } else {
      platformHost =
        (accountInfo.platform_type &&
          PLATFORM_TYPES[accountInfo.platform_type] &&
          PLATFORM_TYPES[accountInfo.platform_type].host) ||
        '';
    }
    if (origin === 'list') {
      return (
        <React.Fragment>
          <YunxiaoIcon type="success-fill" className={`${prefix}-top-left-icon`} />
          <span className={`${prefix}-top-left-text`}>
            {intl.get({
              id: 'code-assets.importProjectModal.accountMessage.Bound',
              defaultMessage: '已绑定',
            })}{' '}
            {accountInfo.platform_type === 'PRIVATE_GITLAB' ? (
              <a target="_blank" href={platformHost} rel="noreferrer">
                {platformHost}
              </a>
            ) : (
              platformName
            )}{' '}
            {intl.get({
              id: 'code-assets.importProjectModal.accountMessage.Account',
              defaultMessage: '帐号：',
            })}
          </span>
          <Button
            type="primary"
            text
            component="a"
            href={platformHost}
            target="_blank"
            className={`${prefix}-top-left-user-name`}
          >
            {accountInfo.import_account_user_name}
          </Button>
          {/* 需要跳转tb的不需要二次确认，token方式需要确认 */}
          {accountInfo.platform_type === 'ALIYUN' ? null : (
            <React.Fragment>
              {accountInfo.bind_type === 'TOKEN' ? (
                <BalloonConfirm
                  type="warning"
                  align="bl"
                  title={intl.get({
                    id: 'code-assets.importProjectModal.accountMessage.Unbind',
                    defaultMessage: '解除绑定',
                  })}
                  content={intl.get({
                    id: 'code-assets.importProjectModal.accountMessage.AreYouSureYouWant',
                    defaultMessage: '确定解除绑定 ？',
                  })}
                  triggerType="click"
                  size="large"
                  trigger={
                    <Button type="primary" className={`${prefix}-top-left-untying `} text>
                      {intl.get({
                        id: 'code-assets.importProjectModal.accountMessage.Unbind',
                        defaultMessage: '解除绑定',
                      })}
                    </Button>
                  }
                  okFn={this.handleUnbind}
                  followTrigger
                />
              ) : (
                <Button
                  type="primary"
                  className={`${prefix}-top-left-untying `}
                  text
                  onClick={() => {
                    this.handleUnbind();
                  }}
                >
                  {intl.get({
                    id: 'code-assets.importProjectModal.accountMessage.Unbind',
                    defaultMessage: '解除绑定',
                  })}
                </Button>
              )}
            </React.Fragment>
          )}
        </React.Fragment>
      );
    }
    return (
      <Message
        title={
          <div>
            {intl.get({
              id: 'code-assets.importProjectModal.accountMessage.Bound',
              defaultMessage: '已绑定',
            })}
            {platformName}
            {intl.get({
              id: 'code-assets.importProjectModal.accountMessage.Account',
              defaultMessage: '帐号：',
            })}
            <a target="_blank" href={platformHost} rel="noreferrer">
              {accountInfo.import_account_user_name}
            </a>
          </div>
        }
        handler={
          accountInfo.platform_type !== 'ALIYUN' ? (
            <Button
              type="primary"
              text
              onClick={() => {
                this.handleUnbind();
              }}
            >
              {intl.get({
                id: 'code-assets.importProjectModal.accountMessage.Unbind',
                defaultMessage: '解除绑定',
              })}
            </Button>
          ) : null
        }
        type="notice"
        className="bound-account-message"
      />
    );
  }
}
